<template>
    <!-- {{
            JSON.stringify(answer)
    }} -->
    <n-page-header @back="handleBack">
        <template #title>
            {{ examDetail.title }}
        </template>
        <template #subtitle>
            <n-space>
                <n-tag type="info" v-if="new Date(examDetail.startTime) > new Date()">
                    未开始
                </n-tag>
                <n-tag type="success"
                    v-if="new Date(examDetail.endTime) > new Date() && new Date(examDetail.startTime) < new Date()">
                    进行中
                </n-tag>
                <n-tag type="error" v-if="new Date(examDetail.endTime) < new Date()">
                    已结束
                </n-tag>
                <n-tag type="info">
                    {{ curTime }}
                </n-tag>
            </n-space>
        </template>

        <template #footer>

        </template>
    </n-page-header>
    <n-grid :cols="12" item-responsive responsive="screen">
        <n-gi span="12 m:10 l:8" offset="0 m:1 l:2">
            <n-layout has-sider sider-placement="right">
                <n-layout-content>
                    <template v-for="(question,index) in examDetail.questions">
                        <n-card>
                            <n-space vertical>
                                <!-- 标题 -->
                                <n-space>
                                    <n-tag type="info" size="small">
                                        {{index+1+'.'}}
                                        {{ questionValueKey[question['type']] }}
                                        ( {{ question['score'] + '分' }} )
                                    </n-tag>
                                    {{ question.title }}
                                </n-space>
                                <!-- 内容 -->
                                <n-space>
                                    <div v-html='question.content'>
                                    </div>
                                </n-space>
                                <!-- 选项 -->
                                <n-space>
                                    <template v-if="question.type == 0">
                                        <n-radio-group v-model:value="answer[question.QID.toString()]" 
                                            name="radiogroup">
                                            <n-space vertical>
                                                <n-radio v-for="option in question.realOptions" :key="option.value"
                                                    :value="option.value">
                                                    {{ option.label }}
                                                </n-radio>
                                            </n-space>
                                        </n-radio-group>
                                    </template>
                                    <template v-if="question.type == 1">
                                        <n-checkbox-group v-model:value="answer[question.QID.toString()]" >
                                            <n-space vertical>
                                                <n-checkbox v-for="option in question.realOptions" :value="option.value"
                                                    :label="option.label">

                                                </n-checkbox>
                                            </n-space>
                                        </n-checkbox-group>
                                    </template>
                                    <template v-if="question.type == 2">
                                        <n-radio-group v-model:value="answer[question.QID.toString()]"
                                            name="radiogroup" >
                                            <n-space>
                                                <n-radio key="true" value="true">
                                                    正确
                                                </n-radio>
                                                <n-radio key="false" value="false">
                                                    错误
                                                </n-radio>
                                            </n-space>
                                        </n-radio-group>
                                    </template>
                                    <template v-if="question.type == 3">
                                        <n-input v-model:value="answer[question.QID.toString()]" ></n-input>
                                    </template>
                                    <template v-if="question.type == 4">
                                        <QuillEditor :options="EditorOptions" :ref="(el)=>{itemRefs[question.QID.toString()] = el}"
                                            v-model:content="answer[question.QID.toString()]" style="height: 250px"
                                            class="quillEditor" />
                                    </template>
                                </n-space>
                            </n-space>
                            
                        </n-card>
                    </template>
                    <n-button type="primary" @click="handleSubmit">提交作答</n-button>
                </n-layout-content>
                <n-layout-sider collapse-mode="transform" :collapsed-width="100" :width="240" :native-scrollbar="false"
                    show-trigger="bar" content-style="padding: 24px;" bordered>
                    
                        <n-grid cols="1 m:4" item-responsive responsive="screen">
                            <n-gi v-for="(question,index) in examDetail.questions" >
                                <n-avatar v-if="answer[question['QID']]" :style="{
                                    backgroundColor: 'green'
                                }">
                                    {{ index+1 }}
                                </n-avatar>
                                <n-avatar v-else>
                                    {{ index+1 }}
                                </n-avatar>
                            </n-gi>
                        </n-grid>
                        
                </n-layout-sider>
            </n-layout>
        </n-gi>
    </n-grid>
</template>
<script lang="ts" setup>
import { getExamDetail } from '@/api/student/exam';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { QuillEditor } from '@vueup/vue-quill';
import { useDialog, useMessage } from 'naive-ui';
import { http } from '@/utils/http/axios';

const route = useRoute();
const router = useRouter();
const curTime = ref();
const EditorOptions = reactive({
    modules: {
        toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block'],

            [{ header: 1 }, { header: 2 }], // custom button values
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
            [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
            [{ direction: 'rtl' }], // text direction

            [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
            [{ header: [1, 2, 3, 4, 5, 6, false] }],

            [{ color: [] }, { background: [] }], // dropdown with defaults from theme
            [{ font: [] }],
            [{ align: [] }],
            ['clean'],
            ['image'],
        ],
    },
    theme: 'snow',
    placeholder: '输入您喜欢的内容吧！',
});

const itemRefs:any=ref({});

const questionValueKey = {
    0: '单选',
    1: '多选',
    2: '判断',
    3: '填空',
    4: '简答'
}

const quillContent = ref();
const answer = ref({});
const examDetail: any = ref({
    questions: []
});

onMounted(async () => {
    examDetail.value = await getExamDetail({ EID: route.params.EID });
    for (let questionKey in examDetail.value['questions']) {

        if (examDetail.value['questions'][questionKey]['type'] == 0 || examDetail.value['questions'][questionKey]['type'] == 1) {
            examDetail.value['questions'][questionKey]['realOptions'] = [];
            for (let optionKey in examDetail.value['questions'][questionKey]['options']) {
                examDetail.value['questions'][questionKey]['realOptions'].push({
                    label: examDetail.value['questions'][questionKey]['options'][optionKey].content,
                    value: examDetail.value['questions'][questionKey]['options'][optionKey].key
                })
            }
            
        }
    }
    if(examDetail.value['preAnswer']){
        // examDetail.value['preAnswer'].forEach(element => {
        //     answer[element.QID.toString()] = element.answer;
        // });
    
    for (let questionKey in examDetail.value['preAnswer']){
            if(examDetail.value['preAnswer'][questionKey]['answer'] === true){
                examDetail.value['preAnswer'][questionKey]['answer'] = 'true';
            }
            if(examDetail.value['preAnswer'][questionKey]['answer'] === false){
                examDetail.value['preAnswer'][questionKey]['answer'] = 'false';
            }
           answer.value[examDetail.value['preAnswer'][questionKey]['QID']] = examDetail.value['preAnswer'][questionKey]['answer'];
        
    }
}
})

setInterval(
    () => {
        let time = (new Date(examDetail.value.endTime).getTime()) - (new Date().getTime());
        let day = new Date(time).getDay();
        let hour = new Date(time).getHours();
        let minute = new Date(time).getMinutes();
        let second = new Date(time).getSeconds();
        curTime.value = '剩余';
        if (day > 0) curTime.value += day + '天';
        if (hour > 0) curTime.value += hour + '小时';
        if (minute > 0) curTime.value += minute + '分';
        if (second > 0) curTime.value += second + '妙';
    },
    100
)

function handleBack() {
    router.go(-1);
}

const message = useMessage();

const dialog = useDialog();
function handleSubmit(){
    let unFinish =0 ;
    examDetail.value.questions.forEach(element => {
                if(answer.value[element['QID']]==null) unFinish++;
            });
    dialog.info({
        title: '提示',
        content: `还有`+unFinish+`道题未完成您想提交这道题吗`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            //message.success('删除成功');
            let params:any = [];
            examDetail.value.questions.forEach(element => {
                if(element.type==4){
                    quillContent.value = answer.value[element['QID']];
                    params.push({
                        QID:element['QID'],
                        //answer:quillEditor.value.getHTML(),
                        answer:answer.value[element['QID']],
                    })
                }else if(element.type==2){
                    let boolValue = true;
                    if(answer.value[element['QID']] == 'false') boolValue=false;
                    params.push({
                        QID:element['QID'],
                        answer:boolValue,
                    })
                }else
                {
                    params.push({
                        QID:element['QID'],
                        answer:answer.value[element['QID']],
                    })
                }
            });
            console.log(params)
            http.request(
                {
                    url:'/student/student_exam/submitExam',
                    method:'post',
                    params:{studentExam:params,EID:route.params.EID}
                }
            ).then(
                ()=>{
                    message.success('成功!');
                    router.go(-1);
                }
            );
        },
        onNegativeClick: () => { },
    });
}
</script>

<style lang="less">
.ql-toolbar.ql-snow {
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: 1px solid #eee;
    margin-top: -10px;
}

.ql-container.ql-snow {
    border: none;
}
</style>
